package com.cheneyjoo.dao;

import com.cheneyjoo.model.QuestionAnswer;
import com.cheneyjoo.model.UserExamAnswer;
import com.cheneyjoo.util.Repository;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class UserExamAnswerDao {
    private static List<UserExamAnswer> userExamAnswers = new ArrayList<>();
    /**
     * 初始化数据信息
     *
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public UserExamAnswerDao() throws IOException, ClassNotFoundException {
        File repositoryFile = Repository.getRepositoryFile("Exam.UserExamAnswer.txt");
        if (userExamAnswers.size() == 0 && repositoryFile.length() != 0) {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(repositoryFile));
            userExamAnswers = (List<UserExamAnswer>) ois.readObject();
            ois.close();
        }
    }

    /**
     * 获取成绩
     *
     * @param
     * @return
     */
    public List<UserExamAnswer> getUserExamAnswers() {
        return userExamAnswers;
    }

    /**
     * 获取学生成绩
     *
     * @param
     * @return
     */
    public List<UserExamAnswer> getUserExamAnswers(int userID) {
        return userExamAnswers.stream().filter(s -> s.getUserID() == userID).collect(Collectors.toList());
    }


    /**
     * 添加成绩
     *
     * @param userExamAnswer
     * @return
     */
    public boolean addUserExamAnswer(UserExamAnswer userExamAnswer) {
        int totalScore=0;
        List<QuestionAnswer> questionAnswers = userExamAnswer.getQuestionAnswers();
        for (QuestionAnswer item:questionAnswers) {
            if (item.getQuestion().getRightAnswer().equals(item.getUserAnswer())){
                item.setRight(true);
                totalScore+=item.getQuestion().getScore();
            }else item.setRight(false);
        }
        userExamAnswer.setSumScore(totalScore);
        if(userExamAnswers.add(userExamAnswer)){
            FlushData();
            return true;
        }else{
            return false;
        }
    }

    /**
     * 刷新数据
     */
    private void FlushData() {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(Repository.getRepositoryFile("Exam.UserExamAnswer.txt")));
            oos.writeObject(userExamAnswers);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
